<div class="item-form-list ItemFormWidget_item_{$field.name}_box">
    <input type="hidden" name="{$field.name}" value='{$field["value"]}'/>
    <table class="table mb0 todo-list">
        <thead>
            <tr>
                <?php foreach($field['js'] as $itemName):?>
                <th style="min-width: auto;">{$itemName}</th>
                <?php endforeach;?>
                <th>操作</th>
            </tr>
        </thead>

        <tbody id="ItemFormWidget_item_{$field.name}_items">

        </tbody>
    </table>
    <div id="ItemFormWidget_item_{$field.name}_last" class="text-center" style="padding-bottom: 10px;">
        <button type="button" class="btn btn-default btn-flat ItemFormWidget_item_{$field.name}_add"><i class="glyphicon glyphicon-plus"></i>&nbsp;&nbsp;新增</button>
    </div>
</div>
<style>
    .sort-highlight{
        height: 51px;
    }
</style>

<script>
    (function(){
        var field="{$field.name}";
        var basePrefix="ItemFormWidget_item_"+field+"_";
        var ItemFormWidget=function(){
            this.containerClass=basePrefix+"box";
            this.addBtnClass=(basePrefix+'add');
            this.delBtnClass=(basePrefix+'del');
            this.container=$(this.containerClass);
            this.inputEle=$('.'+basePrefix+'box input');
            this.inputNamePrefix="_formWidget_";
            this.items=JSON.parse('<?php echo json_encode($field["js"])?:"[]";?>');
        };
        ItemFormWidget.prototype={
            init:function(){
                var context=this;
                //add item
                $('.'+context.containerClass).delegate('.'+context.addBtnClass,'click',function(){
                    context.add();
                    context.sync();
                    return false;
                });
                //del item
                $('.'+context.containerClass).delegate('.'+context.delBtnClass,'click',function(){
                    context.del(this);
                    context.sync();
                    return false;
                });
                //input val sync
                $('.'+context.containerClass).delegate('input','keyup',function(){
                    context.sync();
                });
                //default val load
                context.load();
            },
            sort: function(){
                var context = this;
                $('.'+context.containerClass+ " .todo-list tbody").each(function(){
                    $(this).sortable({
                      //设置当排序动作发生时，空白占位符的CSS样式
                      placeholder: "sort-highlight",
                      //指定在排序对象中，哪些元素是可以进行拖拽排序的。
                      items: "tr:not(p)",
                      //设置在排序动作发生时，元素的z-index值
                      zIndex: 999999,
                      //限制排序的动作只能在item元素中的某个元素开始。
                      handle: ".btn",

                      forcePlaceholderSize: true,
                      //当排序动作结束时且元素坐标已经发生改变时触发此事件。
                      update: function(event, ui) {
                          context.sync();
                      },
                    });
                });

            },
            del:function(a) {
                $(a).parent().parent().parent().parent().remove();
            },
            add:function(dataItem) {
                var context=this;
                if ($('.'+context.containerClass+' .ItemFormWidget_item_i:last').length > 0) {
                    var pos = parseInt($('.'+context.containerClass+' .ItemFormWidget_item_i:last').attr('data-key')) + 1;
                } else {
                    var pos = 1;
                }
                var itemInputEle="";
                var itemInputName="";
                for(var itemKey in context.items){
                    itemInputName='_formWidget_'+itemKey;
                    itemInputEle+=('<td><input name="'+itemInputName+'" value="'+(dataItem?dataItem[itemKey]:'')+'" type="text" class="form-control form-control-lg"></td>');
                }
                var html = '<tr class="ItemFormWidget_item_i" data-key="' + pos + '">\
                                                        '+itemInputEle +'\
                                                        <td style="width:10%">\
                                                                <div class="input-group" style="width:100%;">\
                                                                        <span class="input-group-btn">\
                                                                        <button class="btn btn-icon btn-default btn-flat '+context.delBtnClass+'" type="button"><i class="fa fa-trash-o"></i></button>\
                                                                        <span class="btn btn-icon btn-default btn-flat handle" type="button"><i class="fa fa-ellipsis-v"></i><i class="fa fa-ellipsis-v"></i></span>\
                                                                </span>\
                                                        </div></td>\
                                                </tr>';
                $('#'+basePrefix+'items').append(html);
            },
            load:function(){
                var defaultVal=this.inputEle.val();
                defaultVal=defaultVal?JSON.parse(defaultVal):[];
                defaultVal = defaultVal || [];
                for(var i=0;i<defaultVal.length;i++){
                    this.add(defaultVal[i]);
                }
                if(!defaultVal||defaultVal.length==0){
                    this.add();
                }

                // 拖拽排序
                this.sort();
            },
            sync:function(){
                var data=[];
                var item={};
                var context=this;
                $('#'+basePrefix+'items .ItemFormWidget_item_i').each(function(){
                    item={};
                    $(this).find('input').each(function(){
                        item[$(this).attr('name').replace(context.inputNamePrefix,'')]=$(this).val();
                    });
                    data.push(item);
                });
                this.inputEle.val(JSON.stringify(data));
            },
        };
        new ItemFormWidget().init();
    })();
</script>
